<?
// Clean user input from form fields
function fieldToDB($string,$urlClick=null) {
	// Trim whitespace
		$string = trim(stripslashes($string));
	// Check for HTML characters
		$string = str_replace(Chr(10), '{lb}', $string);
		$string = str_replace('\r\n', '{lb}', $string);
		$string = htmlspecialchars($string,ENT_QUOTES,"UTF-8");
	// Make URL's clickable if required
		if ($urlClick == 1) {
			$string = parseURLS($string,false,'_blank');	
		}	
	
	// Prevent SQL injection
		$string = mysql_real_escape_string($string);	
	// Insert line breaks if needed
		$string = str_replace('{lb}', '<br>', $string);
	
	return $string;
}

function DBToField($string) {
	//$string = htmlspecialchars_decode($string,ENT_QUOTES);
	$string = str_replace('&quot;', '"', $string);
	$string = str_replace('&#039;', '\'', $string);
	// Insert line breaks
	$string = str_replace('<br>', chr(10), $string);
	$string = str_replace('<br>', '\n', $string);
	// Replace HTML entities characters with HTML
	$string = stripslashes($string);
	return $string;
}

function DBToCSV($string) {
	//$string = str_replace('&quot;', '"', $string);
	//$string = str_replace('&#039;', '\'', $string);
	
	$string = str_replace('&amp;', '&', $string);
	$string = html_entity_decode($string);
	// Insert line breaks
	$string = str_replace('<br>', ' ', $string);
	$string = str_replace('<br />', ' ', $string);
	// Get rid of any HTML tags
	$string = strip_tags($string);
	$string = stripslashes($string);
	return $string;
}

function DBToTXT($string) {
	$string = html_entity_decode($string);
	// Insert line breaks
	$string = str_replace('&amp;', '&', $string);
	$string = str_replace('<br>', "\r\n", $string);
	$string = str_replace('<br />', "\r\n", $string);
	// Get rid of any HTML tags
	$string = strip_tags($string);
	$string = stripslashes($string);
	return $string;
}

function DBToMail($string) {
	// Insert line breaks
	$string = str_replace('&amp;', '&', $string);
	$string = str_replace('&#39;', '\'', $string);
	$string = str_replace('<br>', Chr(10), $string);
	$string = str_replace('<br />', Chr(10), $string);
	
	// Get rid of any HTML tags
	$string = strip_tags($string);
	$string = stripslashes($string);
	return $string;
}

// Great little function that converts plain text url's into clickable url's
// url's must be in the form of http://..... 
// By Nico : May be found at http://www.bytemycode.com/snippets/snippet/602/
function parseURLS($text, $maxurl_len = 35, $target = '_self') {
    if (preg_match_all('/((ht|f)tps?:\/\/([\w\.]+\.)?[\w-]+(\.[a-zA-Z]{2,4})?[^\s\r\n\(\)"\'<>\,\!]+)/si', $text, $urls)) {
        $offset1 = ceil(0.65 * $maxurl_len) - 2;
        $offset2 = ceil(0.30 * $maxurl_len) - 1;
       
        foreach (array_unique($urls[1]) AS $url) {
            if ($maxurl_len AND strlen($url) > $maxurl_len) {
                $urltext = substr($url, 0, $offset1) . '...' . substr($url, -$offset2);
            }
            else { $urltext = $url; }
           
            $text = str_replace($url, '<a href="'. $url .'" target="'. $target .'" title="'. $url .'">'. $urltext .'</a>', $text);
        }
    }
    return $text;
}

// Determine Browser
function getBrowser() {
	$browser = strstr(getenv('HTTP_USER_AGENT'), 'MSIE');
	if (!empty($browser)) {
		// Check for Opera browser
		$opera = strstr(getenv('HTTP_USER_AGENT'), 'Opera');
		if (!empty($opera)) {
			$browser = "Mozilla"; 
			$stylesheet = "stylesMozilla.css?".random_string(5);
			$jpeg_mime_type = "image/jpeg";
		} else {
			$browser = "IE"; 
			$stylesheet = "stylesIE.css?".random_string(5);
			$jpeg_mime_type = "image/pjpeg";
		}	
	} else {
		$browser = "Mozilla"; 
		$stylesheet = "stylesMozilla.css?".random_string(5);
		$jpeg_mime_type = "image/jpeg";
	}
}
	
// Better mail function
function mailNew($fromName, $fromAddress, $to, $subject, $message) {
   // Copyright ? 2005 ECRIA LLC, http://www.ECRIA.com
   // Please use or modify for any purpose but leave this notice unchanged.
   $headers  = "MIME-Version: 1.0\n";
   $headers .= "Content-type: text/plain; charset=iso-8859-1\n";
   $headers .= "X-Priority: 3\n";
   $headers .= "X-MSMail-Priority: Normal\n";
   $headers .= "X-Mailer: php\n";
   $headers .= "From: \"".$fromName."\" <".$fromAddress.">\n";
   return mail($to,$subject,$message,$headers);
}

// Function to prevent email form injection attacks
function emailPreventInjection($input) {
	$repl = '';
	$input = (ereg_replace("\r", $repl, $input));
	$input = (ereg_replace("\n", $repl, $input));
	$input = (ereg_replace("%0a", $repl, $input));
	$input = (ereg_replace("%0d", $repl, $input));
	$input = (ereg_replace("Content-Type:", $repl, $input));
	$input = (ereg_replace("bcc:", $repl, $input));
	$input = (ereg_replace("to:", $repl, $input));
	$input = (ereg_replace("cc:", $repl, $input));
	return $input;
} 

// Check for valid email address
function checkValidEmail($email) { 
	$exp = "^[a-z\'0-9]+([._-][a-z\'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$";
	
	if(eregi($exp,$email)) {
		$host = explode('@', $email);
		if(checkdnsrr($host[1].'.', 'MX') ) return true;
		//if(checkdnsrr($host[1].'.', 'A') ) return true;
		//if(checkdnsrr($host[1].'.', 'CNAME') ) return true;
	}
	return false;
}

function commaDelEmailToArray($emailString) {
	$emailArray = explode(',',$emailString);
	array_walk($emailArray,'trimValues');
	return $emailArray;
}

function trimValues(&$value) {
	$value = trim($value);
}

// Generate a random string 
function random_string($length,$type=null) {
	global $string;
	// Generate Random Password
	mt_srand ((double) microtime() * 1000000);
	$possibleAlpha   = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
	$possibleNumeric = '0123456789';
	$possibleChar    = '~!@#$%^&*()_+';
	
	if (empty($type)) {
		$possible = $possibleAlpha.$possibleChar.$possibleNumeric;
	} elseif ($type == 'alpha') {
		$possible = $possibleAlpha;
	} elseif ($type == 'numeric') {
		$possible = $possibleNumeric;
	} elseif ($type == 'char') {
		$possible = $possibleChar;
	}
	
	$string = "";
	
	while (strlen($string) < $length) {
		$no_add = 0;
		$str = substr($possible, mt_rand(0, strlen($possible) - 1), 1);
		// Check that preceeding character in $password is not same as current character
				
		if (strlen($string) >= 1) {
			for ($a=1;$a<=strlen($string);$a++) {
				// $str will be current character
				if ($str == substr("$string", -$a, 1)) { $no_add = 1; }
			} // End For Loop
		} // End If
		
		if ($no_add == 1) { continue; }
		$string .= $str; // Build the password string
	} // End While loop
	return $string;
}

// Function Resize_image()
// This function accepts a jpeg image, resizes it according to a scaling factor
// and then copies it to a new file with a specified filename "extension"
// Ex. resize_image(image.jpg, 100, thumb) 
// This would generate a new JPEG file called thumb_image.jpg at 100 pixels wide

function resize_image($orig_file,$max_width,$max_height,$file_ext,$dir,$border,$mime) {
	// Determine filenames
	$fileArray = explode("/", $orig_file);
	$file_elements = count($fileArray);
	$last_element = $file_elements - 1;
	if (!empty($file_ext)) {
		$out_file = $file_ext."_".$fileArray[$last_element];
	} else {
		$out_file = $fileArray[$last_element];
	}	
	
	// Rebuild directory string for thumbnail file
	$directory = "";
	for ($a=0;$a<=($last_element - 1);$a++) {
		if (empty($directory)) {
			$directory = $fileArray[$a];
		} else {
			$directory = $directory."/".$fileArray[$a];
		}		
	}
	if (!empty($dir)) { $directory = $directory."/".$dir; }
	
	$out_file = $directory."/".$out_file;	
		
	$size = getimagesize($orig_file);
	if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
		$im_in = imagecreatefromjpeg($orig_file);
	} elseif ($mime == "image/gif") {
		$im_in = imagecreatefromgif($orig_file);
	} elseif ($mime == "image/png") {
		$im_in = imagecreatefrompng($orig_file);
	}
	
	// Get original image dimentions
	$origW = $size[0];
	$origH = $size[1];
	
	// Get scale %age - we have 3 cases here
	if (!empty($max_width) && !empty($max_height)) {
		// This is gonna be tricky 'cause we want to avoid disportion
		// Do short side first, then figure out other dimention
		if ($origW > $origH) {
			// Horizontal orientation
			// Determine ideal scale
			$scale = floor($max_height / $origH);
			$new_height = $max_height;
			$new_width = $max_width;
			
			$optW = floor($origW*$scale);
			
			// Now we need to first crop image to the right proportions before scaling
			if ($max_width == $max_height) {
				$cropW = $origH;
				$cropH = $origH;							
				$origW = $cropW;
				$origH = $cropH;
			} elseif ($max_width < $max_height) {
				$ratio = $max_width/$max_height;
				$cropW = ($origW*$ratio);
				$cropH = $origH;
				$origW = $cropW;
				$origH = $cropH;
			} elseif ($max_width > $max_height) {
				$ratio = $max_height/$max_width;
				$cropW = $origW;
				$cropH = ($origH*$ratio);
				$origW = $cropW;
				$origH = $cropH;
			}		
			$im_out = imagecreatetruecolor($cropW, $cropH);
			imagecopy($im_out, $im_in, 0, 0, 0, 0, $cropW, $cropH);
			if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
				imagejpeg($im_out, $out_file, 100);
				$im_in = imagecreatefromjpeg($out_file);
			} elseif ($mime == "image/gif") {
				imagegif($im_out, $out_file, 100);
				$im_in = imagecreatefromgif($out_file);
			} elseif ($mime == "image/png") {
				imagepng($im_out, $out_file, 100);
				$im_in = imagecreatefrompng($orig_file);
			}						
				
		} elseif ($origW < $origH) {
			// Vertical orientation
			// Determine ideal scale
			$scale = floor($max_width / $origW);
			$new_width = $max_width;
			$new_height = $max_height;
			
			$optH = floor($origH*$scale);
			
			// Now we need to first crop image to the right proportions before scaling
			if ($max_width == $max_height) {
				$cropW = $origW;
				$cropH = $origW;							
				$origW = $cropW;
				$origH = $cropH;			
			} elseif ($max_width < $max_height) {
				$ratio = $max_width/$max_height;
				$cropW = ($origW*$ratio);
				$cropH = $origH;
				$origW = $cropW;
				$origH = $cropH;
			} elseif ($max_width > $max_height) {
				$ratio = $max_height/$max_width;
				$cropW = $origW;
				$cropH = ($origH*$ratio);
				$origW = $cropW;
				$origH = $cropH;
			}			
			$im_out = imagecreatetruecolor($cropW, $cropH);
			imagecopy($im_out, $im_in, 0, 0, 0, 0, $cropW, $cropH);
			if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
				imagejpeg($im_out, $out_file, 100);
				$im_in = imagecreatefromjpeg($out_file);
			} elseif ($mime == "image/gif") {
				imagegif($im_out, $out_file, 100);
				$im_in = imagecreatefromgif($out_file);
			} elseif ($mime == "image/png") {
				imagepng($im_out, $out_file, 100);
				$im_in = imagecreatefrompng($out_file);
			}			
		} elseif ($origW == $origH) {
			// Square - easy
			$new_width = $max_width;
			$new_height = $max_height;
		}
	} elseif (!empty($max_width) && empty($max_height)) {	
		$scale = ($max_width / $origW);
		$new_width = $max_width;
		$new_height = floor($origH * $scale);
	} elseif (!empty($max_height) && empty($max_width)) {
		$scale = ($max_height / $origH);
		$new_height = $max_height;
		$new_width = floor($origW * $scale);
	}
		
	$im_out = imagecreatetruecolor($new_width, $new_height);
	imagecopyresized($im_out, $im_in, 0, 0, 0, 0, $new_width, $new_height, $origW, $origH);
	if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
		imagejpeg($im_out, $out_file, 100);
	} elseif ($mime == "image/gif") {
		imagegif($im_out, $out_file, 100);
	} elseif ($mime == "image/png") {
		imagepng($im_out, $out_file, 100);
	}
	
	// Draw border
	if (!empty($border)) {
		if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
			$im_in =  imagecreatefromjpeg($out_file);
		} elseif ($mime == "image/gif") {
			$im_in =  imagecreatefromgif($out_file);
		} elseif ($mime == "image/png") {
			$im_in =  imagecreatefrompng($out_file);
		}
		$color = ImageColorAllocate($im_in,0,0,0);
		ImageLine($im_in,0,0,($max_width-1),0,$color); // Top
		ImageLine($im_in,($max_width-1),1,($max_width-1),($max_height-1),$color); // Right
		ImageLine($im_in,($max_width-1),($max_height-1),1,($max_height-1),$color); // Bottom
		ImageLine($im_in,0,($max_height-1),0,0,$color); // Left
		if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
			imagejpeg($im_in, $out_file, 100);
		} elseif ($mime == "image/gif") {
			imagegif($im_in, $out_file, 100);
		} elseif ($mime == "image/png") {
			imagepng($im_in, $out_file, 100);
		}
	}
	
	imagedestroy($im_out);
	imagedestroy($im_in);	
}

// Calculates number of days between 2 dates.
function daysBetweenDates($dateStart,$dateEnd) {
	global $days;
	$dateStartArray = explode("-",$dateStart);
	$dateEndArray = explode("-",$dateEnd);
	
	$startYear = $dateStartArray[0];
	$startMonth = $dateStartArray[1];
	$startDay = $dateStartArray[2];
	
	$endYear = $dateEndArray[0];
	$endMonth = $dateEndArray[1];
	$endDay = $dateEndArray[2];
	
	//first convert to unix timestamp
	$init_date = mktime(12,0,0,$startMonth,$startDay,$startYear);
	$dst_date = mktime(12,0,0,$endMonth,$endDay,$endYear);

	$offset = $dst_date-$init_date; //Depending on which offset type you want, switch order

	$days = floor($offset/60/60/24); 
	return $days;
}

function dateFromDays($dateStart,$days) {
    // Convert $dateStart to timestamp
    $dateStartArray = explode("-",$dateStart);
   
    $startYear = $dateStartArray[0];
    $startMonth = $dateStartArray[1];
    $startDay = $dateStartArray[2];
   
    $initTimeStamp = mktime(12,0,0,$startMonth,$startDay,$startYear);
    $endTimeStamp  = $initTimeStamp + ($days*60*60*24);
   
    // Convert $endTimeStamp to date
    $dateEnd = date('Y-m-d',$endTimeStamp);
   
    return $dateEnd;
}

// Shortens a string of text to be only $words long.
function shortText($text,$words) {
	$text = strip_tags($text,'<a>');
	$textArray = explode(" ", $text);
	
	$noOfWords = count($textArray);

	if ($noOfWords<$words) {
		return $text;
	} else {
		$newText = null;
		for($zz=0;$zz<=($words);$zz++) {
			$newText .= $textArray[$zz]." ";
		}
		$shortText = $newText."...";
		
		return $shortText;
	}	
}

// A piss-poor pagination function.
function paginate($pages,$perPage,$urlString,$page,$pageNoOnly) {
	if ($pageNoOnly == 1) {
		echo "Page: ";
		for($p=1;$p<=$pages;$p++) {
			if ($p>1) { $start = ($p-1)*$perPage; }
			else { $start = 0; }
			if ($page == $p) { echo "<span class=orange><b>$p</b></span>\n"; }
			else { echo "<a href=\"$PHP_SELF?page=$p&start=$start".$urlString."\"><b>$p</b></a>\n"; }
			if ($p < $pages) { echo " <font color=#c0c0c0>|</font> \n"; }
		}
	} else {
		echo "<div class=\"grayField\" style=\"text-align: right;\">Page: \n";
		for($p=1;$p<=$pages;$p++) {
			if ($p>1) { $start = ($p-1)*$perPage; }
			else { $start = 0; }
			if ($page == $p) { echo "<span class=orange><b>$p</b></span>\n"; }
			else { echo "<a href=\"$PHP_SELF?page=$p&start=$start".$urlString."\"><b>$p</b></a>\n"; }
			if ($p < $pages) { echo " <font color=#c0c0c0>|</font> \n"; }
		}
		echo "</div>\n";
	}	
}

// Hmm, not sure what this does.
function microtime_float() {
   list($usec, $sec) = explode(" ", microtime());
   return ((float)$usec + (float)$sec);
}

// Hover grabs some text from the database based on ID and displays
// content in mouseover popup using overLib javaScript library.
// TODO: Rewrite function hoverHelp to use ExtJS
function hoverHelp($type,$hoverID) {
	global $linkHREF, $dbname, $db, $db_selected;
	
	if ($type == "help") {
		// Get content from ss_help
		$sql = "SELECT DEFINITION from DICTIONARY WHERE WORD = '$word' LIMIT 1";
		$result = mysql_db_query($dbname,$sql);
		$rowDef = mysql_fetch_assoc($result);
	} elseif ($type == "message") {
		// Get content from ss_siteMessage
	}		
	$linkHREF = "<a href=\"\" onmouseover=\"return overlib('Hi there', STICKY, CENTER, MOUSEOFF, WRAP, CELLPAD, 5);\" onmouseout=\"return nd();\">\n";
	$defineLink .= "<b>$displayWord</b></a>";
	echo $linkHREF;
	return $linkHREF;
}

function buildBreadcrumbs($path) {
	global $breadCrumbs, $dbname, $db, $db_selected;
	// $path is in the form of /mainCat/subCat/subSubCat
	
	$pathArray = explode('/',$path);
	$mainCat   = $pathArray[1];
	$subCat    = $pathArray[2];
	$subSubCat = $pathArray[3];
	
	$sql = "SELECT * from transLevels WHERE Path = '/$mainCat'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);
	$mainCatName = stripslashes($row[LevelName]);
	
	$sql = "SELECT * from transLevels WHERE Path = '/$mainCat/$subCat'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);
	$subCatName = stripslashes($row[LevelName]);
	
	$sql = "SELECT * from transLevels WHERE Path = '/$mainCat/$subCat/$subSubCat'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);
	$subSubCatName = stripslashes($row[LevelName]);
	
	$breadCrumbs = "$mainCatName : $subCatName : $subSubCatName";
	
	return $breadCrumbs;
}

// Checks for a valid link URL.
function linkChecker($url) {
	global $html;
	$linkInfo  = @parse_url( $url );
	$fp = @fsockopen( $linkInfo["host"], 80, $errno, $errstr, 10 );
	if ( !$fp ) {
		return false;
	} else {
		if( empty( $linkInfo["path"] ) ) {
	        // If it is empty it fills it
	        $linkInfo["path"] = "/";
	     }
	     $query = "";
	
	     // Checks if there is a query string in the url
	     if( isset( $linkInfo["query"] ) ) {
	          // If there is a query string it adds a ? to the front of it
	          $query = "?".$linkInfo["query"]."";
	     }
	
	     // Sets the headers to send
	     $out  = "HEAD ".$linkInfo["path"]."".$query." HTTP/1.0\r\n";
	     $out .= "Host: ".$linkInfo["host"]."\r\n";
	     $out .= "Connection: close \r\n" ;
	     $out .= "User-Agent: link_checker/1.1\r\n\r\n";
	
	     // writes the headers out
	     @fwrite( $fp, $out );
	     $html = '';
	
	     // Reads what gets sent back
	     while ( !@feof( $fp ) ) {
	          $html .= @fread( $fp, 8192 );
	     }
	     // Closes socket
	     fclose( $fp );
	 }    
	 return $html;	
}

// Replaces bad characters in things like filenames and such.
function cleanString($string) {
	global $badCharArray;
	$string   = stripslashes($string);	
	$patArray  = array('&#039;','&amp;','#','$',' ',Chr(39),Chr(35),Chr(38));
	$replArray = array('','','','','_','','','');
	
	$pats = count($badCharArray);
	
	for($a=0;$a<=($pats-1);$a++) {
		$string = (ereg_replace($badCharArray[$a], $replArray[$a], $string));
	} 
		
	$cleanString = $string;
	return $cleanString;
}

// TODO: Find out why this function is in here.
function parse_csv_file($file, $columnheadings = false, $delimiter = ',', $enclosure = null) {
	global $rows;
   $row = 1;
   $rows = array();
   $handle = fopen($file, 'r');
  
   while (($data = fgetcsv($handle, 8000, $delimiter, $enclosure )) !== FALSE) {
       if ($columnheadings == true && $row == 1) {
           $headingTexts = $data;
       }
       elseif ($columnheadings == true) {
           foreach ($data as $key => $value) {
               unset($data[$key]);
               $data[$headingTexts[$key]] = $value;
           }
           $rows[] = $data;
       }
       else {
           $rows[] = $data;
       }
       $row++;
   }
  
   fclose($handle);
   return $rows;
}

function toolTip($ttLabel,$type=null) {
	global $toolTip,$dbname,$db,$db_selected,$pre;

	$sql = "SELECT * from ncdb_sysHelp WHERE BriefDesc = '$ttLabel'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);
	
	$ttText  = stripslashes($row[HelpText]);
	$type   = '0';
	$toolTip = '<SPAN onMouseOver="toolTip(\''.$ttText.'\',\''.$type.'\');" onMouseOut="toolTip()" style="cursor: help;"><img src="'.$pre.'images/icon_help_small.gif"></SPAN>';
	return $toolTip;
}

function extDateToMySQL($date=null) {
	// extDateToMySQL converts a date from the ext date-picker control to MySQL format 
	// MM/DD/YY --> YYYY-MM-DD
	
	if (empty($date)) { 
		$newDate = '0000-00-00';
	} else {
		$dateArray = explode('/',$date);
		$m = $dateArray[0];
		$d = $dateArray[1];
		$y = $dateArray[2];
		
		$newDate = $y.'-'.$m.'-'.$d;
	}	
	return $newDate;	
}

function mySQLToExt($date=null) {
	if ( ($date == '0000-00-00') || empty($date) ) {
		$newDate = '';
	} else {
		$dateArray = explode('-',$date);
		$y = $dateArray[0];
		$m = $dateArray[1];
		$d = $dateArray[2];
		
		$newDate = $m.'/'.$d.'/'.$y;
	}
	return $newDate;
}

function convertFileSize($inFileSize) {
	global $outFileSize;
	
	if ($inFileSize>999999) { $outFileSize = number_format( ($inFileSize/1000000),1).' MB'; }
	elseif ($inFileSize>999) { $outFileSize = number_format( ($inFileSize/1000),1).' KB'; }
	else { $outFileSize = number_format($inFileSize,1).' B';	}
	return $outFileSize;
}

function calcNewNumber($maxNumber) {
	$tNumArray = explode('-',$maxNumber);
	$tNumY  = $tNumArray[0];
	$tNumNo = $tNumArray[1];
	
	if ($tNumY < date('Y')) {
		// We start at new year with Y-0001
		$tNumber = date('Y').'-0001';
	} else {
		// Increment $tNumNo by 1 and that's all;
		$tNumNo++;
		if ($tNumNo < 1000) { $tNumNo = '0'.$tNumNo; }
		if ($tNumNo < 100) { $tNumNo = '0'.$tNumNo; }
		$tNumber = $tNumY.'-'.$tNumNo;
	}	
	return $tNumber;
}

//***** COMMON SAJAX FUNCTIONS **************************************************************/
function makeTinyURL($url,$urlField) {
	global $tinyURL;
	
	$tinySendURL = 'http://tinyurl.com/api-create.php?url='.$url;		
	// fopen method
	$handle = @fopen($tinySendURL, "r");
	if ($handle) {
	    while (!feof($handle)) {
	        $buffer = fgets($handle, 4096);
	        $tinyURL = $buffer;
	    }
	    @fclose($handle);
	}
	$tinyURL = $tinyURL.'|'.$urlField;
	return $tinyURL;
}

function replaceDefaultValues($array) {
	/*
	 * replaceDefaultValues takes an array and replaces all occurences of 
	 * $searchArray[xxx] with $replaceArray[xxx]
	 */
	$searchArray  = array('Select...','Yr','Mo','http://');
	$replaceArray = array('','','','');
	
	for($a=0;$a<=(count($searchArray)-1);$a++) {
		$array = str_replace($searchArray[$a],$replaceArray[$a],$array);
	} 
	
	return $array;	
}

function getStatusInfo($statusCode,$statusType) {
	if ($statusType == 'contact') {
		switch ($statusCode) {
			case 1:
				$statusClass = 'statusOpen';
				$statusText  = 'In progress';
				break;
			case 2:
				$statusClass = 'statusTransferred';
				$statusText  = 'Sent for follow-up';
				break;
			case 3:
				$statusClass = 'statusClosed';
				$statusText  = 'Closed';
				break;	
			case 4:
				$statusClass = 'statusReopen';
				$statusText  = 'Reopened';
				break;	
			case 5:
				$statusClass = 'statusAlert';
				$statusText  = 'Closure Overdue!';
				break;			
		}
	}
	
	$statusArray = array($statusClass,$statusText);
	return $statusArray;
}

function highlightTerm($string, $term) {
    $string = str_ireplace($term, '<span class="highlight_word">'.$term.'</span>', $string);
    
    /*** return the highlighted string ***/
    return $string;
}

function highlightWords($string, $wordArray) {
    foreach ( $wordArray as $word ) {
        $string = str_ireplace($word, '<span class="highlight_word">'.$word.'</span>', $string);
    }
    /*** return the highlighted string ***/
    return $string;
}
 
function setMimeIconClass($fileType) {
	switch ($fileType) {
		case 'application/msword':
			$mimeIconClass = 'mimeIconWord';
			break;
		case 'text/comma-separated-values':
			$mimeIconClass = 'mimeIconExcel';
			break;	
		case 'image/gif':
			$mimeIconClass = 'mimeIconImage';
			break;	
		case 'image/jpeg':
			$mimeIconClass = 'mimeIconImage';
			break;		
		case 'application/octet-stream':
			$mimeIconClass = 'mimeIconDefault';
			break;	
		default: 
			$mimeIconClass = 'mimeIconDefault';
	}
	return $mimeIconClass;
}
?>